﻿using System.Threading.Tasks;
using Service.Model.Context;
using Service.Workflow.GamePlayer.Command;
using Service.Workflow.Player.Command;
using ShortBus;

namespace Service.Workflow.Game.Command
{
    public class CreateGameCommandHandler : IAsyncQueryHandler<CreateGameCommand, CreateGameCommandResponse>
    {
        private readonly IMediator mediator;
        private readonly ServiceDbContext dbContext;

        public CreateGameCommandHandler(IMediator mediator, ServiceDbContext serviceDbContext)
        {
            this.mediator = mediator;
            this.dbContext = serviceDbContext;
        }

        public async Task<CreateGameCommandResponse> HandleAsync(CreateGameCommand command)
        {
            var createPlayer1CommandResponse = await mediator.RequestAsync(new CreatePlayerCommand
            {
                Color = command.Player1Color,
                Difficulty = command.Player1Difficulty,
                Heuristics = command.Player1Heuristics
            });

            var createPlayer2CommandResponse = await mediator.RequestAsync(new CreatePlayerCommand
            {
                Color = command.Player2Color,
                Difficulty = command.Player2Difficulty,
                Heuristics = command.Player2Heuristics
            });


            var game = new Model.Game();

            dbContext.Games.Add(game);

            await dbContext.SaveChangesAsync();

            var createGamePlayer1CommandResponse = await mediator.RequestAsync(new CreateGamePlayerCommand
            {
                GameId = game.GameId,
                PlayerId = createPlayer1CommandResponse.Data.PlayerId
            });

            var createGamePlayer2CommandResponse = await mediator.RequestAsync(new CreateGamePlayerCommand
            {
                GameId = game.GameId,
                PlayerId = createPlayer2CommandResponse.Data.PlayerId
            });

            return new CreateGameCommandResponse()
            {
                GameId = game.GameId
            };
        }
    }
}